// @ts-nocheck
import React, { useRef, useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import md5 from "js-md5";
import { Toast } from "antd-mobile";
import { formdataify } from "@/utils/Axios";
import { login, submit, submit1, update, userAuthInfo } from "../Login/servece";
// import { autoLogin } from "./servece";
import {
  setToken,
  setAccessToken,
  setRefreshToken,
  setCurrentUser,
  setKepperToken,
} from "@/utils/authority";
import "./index.less";

const AutoLogin: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const code = searchParams.get("focus-open-code");
  const [showTips, setShowTips] = useState(false);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    // if (code) {

    // autoLogin({ code })
    //   .then((res) => {
    //     if (res?.code == 200 && res?.data) {
    //       if (typeof res?.data == "string") {
    //         setShowTips(true);
    //       } else {
    //         const {
    //           token_type,
    //           access_token,
    //           refresh_token,
    //           expires_in = 0,
    //           ...users
    //         } = res?.data || {};
    //         localStorage.setItem("users", JSON.stringify({ ...users }));
    //         setToken(`${token_type} ${access_token}`);
    //         setRefreshToken(refresh_token || "");
    //         setAccessToken(access_token);
    //         setCurrentUser(res);
    //         // localStorage.setItem("user_info", JSON.stringify(res));
    //         window.LoginUserInfo = JSON.stringify(res);
    //         sessionStorage.setItem("isFromRzt", true);
    //         navigate("/?code=fromRzt");
    //       }
    //     } else {
    //       throw new Error(res?.msg);
    //     }
    //   })
    //   .catch((err) => {
    //     Toast.show({
    //       icon: "fail",
    //       content: err.toString(),
    //     });
    //   });
    // }
    const value = {
      username: "程金莲",
      password: md5("Guang123@321"),
      tenantId: "000000",
      scope: "all",
      grant_type: "password",
      type: "account",
    };
    const values1 = {
      username: "程金莲",
      password: "Guang123@321",
      tenantId: "000000",
      scope: "all",
      grant_type: "password",
      type: "account",
    };

    submit(formdataify(value))
      .then((data) => {
        // console.log(data);
        if (data?.data?.access_token) {
          const {
            token_type,
            access_token,
            refresh_token,
            expires_in = 0,
            ...users
          } = data?.data || {};
          localStorage.setItem("users", JSON.stringify({ ...users }));
          const time = new Date().getTime();
          setToken(`${token_type} ${access_token}`);
          setRefreshToken(refresh_token || "");
          setAccessToken(access_token);
          setCurrentUser(data);

          submit1(values1).then((res) => {
            if (res.data.code == 200) {
              const tokenArr = document.cookie.split("=");
              setKepperToken(tokenArr[1]);

              Toast.show({
                icon: "success",
                content: res.data.msg,
              });
              login().then((res1) => {
                if (res1.code == 200) {
                  userAuthInfo().then((infoData) => {
                    if (infoData.code == 200) {
                      localStorage.setItem("authFlag", infoData.data.authFlag);
                    }
                  });
                  localStorage.setItem("user_info", JSON.stringify(res1));
                  window.LoginUserInfo = JSON.stringify(res1);

                  navigate("/");
                } else {
                  Toast.show({
                    icon: "fail",
                    content: res1.msg,
                  });
                }
              });
            } else if (
              res.data.code == 400 &&
              res.data.msg == "请修改初始密码"
            ) {
              setItemVisble(true);
            } else {
              Toast.show({
                icon: "fail",
                content: res.data.msg,
              });
            }
          });
        } else {
          Toast.show({
            icon: "fail",
            content: "用户名或密码错误",
          });
          // throw new Error(data.msg)
        }
      })
      .catch((err) => {
        // Toast.show({
        //     icon: 'fail',
        //     content: err.toString(),
        // })
      })
      .finally((all) => {
        setTimeout(() => {
          // setLoading(true);
        }, 2000);
      });
  }, []);

  return (
    <div>
      {showTips && (
        <div className="result">
          <div>
            {" "}
            <img src="/result.png" />
          </div>
          <div className="fail">
            <div>暂无权限</div>
            {/* <div>可联系广安市智慧蓉城运行中心开通。</div> */}
          </div>
        </div>
      )}
    </div>
  );
};

export default AutoLogin;
